package com.willpower.eureka.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.willpower.eureka.entity.SysPassword;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.willpower.eureka.entity.SysUser;
import com.willpower.eureka.mapper.SysPasswordMapper;
import com.willpower.eureka.service.ISysPasswordService;
import com.willpower.eureka.utils.AESCrypt;
import com.willpower.eureka.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wen-yi
 * @since 2021-11-07
 */
@Slf4j
@Service
public class SysPasswordServiceImpl extends ServiceImpl<SysPasswordMapper, SysPassword> implements ISysPasswordService {
    @Autowired
    private RedisUtil redisUtil;
    @Resource
    private SysPasswordMapper sysPasswordMapper;

    @Override
    public JSONObject selectPage(Integer id,String query, Integer pageNum, Integer pageSize) {
        JSONObject json = new JSONObject();
        LambdaQueryWrapper<SysPassword> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysPassword::getOwner,id);
        wrapper.select(SysPassword::getId,SysPassword::getCloudType,SysPassword::getCloudIp,SysPassword::getExecuteType,
                SysPassword::getUsername,SysPassword::getOut,SysPassword::getComment);
        if (StrUtil.isNotEmpty(query)){
            wrapper.like(SysPassword::getCloudType, query).or().like(SysPassword::getExecuteType, query)
                    .or().like(SysPassword::getUsername,query).or().like(SysPassword::getComment,query);
        }
        Page<SysPassword> page = sysPasswordMapper.selectPage(new Page<>(pageNum, pageSize), wrapper);
        List<SysPassword> records = page.getRecords();

        json.put("status", true);
        json.put("code", 200);
        json.put("msg", "成功");
        json.put("data", records);
        json.put("pageNum", pageNum);
        json.put("total", page.getTotal());
        return json;
    }

    @Override
    public String getPasswordById(Integer id, String verifyCode) {
        String password = null;
        try {
            String redisCode = redisUtil.get("aj");
            if (StrUtil.equals(redisCode, verifyCode)){
                password = AESCrypt.decryptByAES(sysPasswordMapper.getPassword(id));
            }
        } catch (Exception e){
            e.printStackTrace();
        }
        return password;
    }
}
